import { message } from 'antd';
import Mock from 'mockjs'
import useRequest from '../../packages/useRequest';

function editUsername(username: string): Promise<string> {
  console.log('editUsername', username);
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (Math.random() > 0.5) {
        resolve(Mock.mock('@name'));
      } else {
        reject(new Error('抛出错误'));
      }
    }, 1000);
  });
}

export default function Demo2() {
  const { data, loading, run } = useRequest(editUsername, {
    manual: true,
    onSuccess: (result, params) => {
      console.log(result);
      message.success(`onSuccess 执行 "${params[0]}" !`);
    },
    onError: (error) => {
      message.error(`onError 执行 ${error.message}`);
    },
  });

  return (
    <div>
      <p>执行结果：{data}</p>
      <button disabled={loading} type="button" onClick={() => run('')}>
        {loading ? 'Loading' : '手动执行run'}
      </button>
    </div>
  );
}
